<template>
  <div class="login-container">
    <van-nav-bar
      title="黑马头条"
      left-text="返回"
      left-arrow
      right-text="设置"
      :fixed="true"
    />

    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号名' },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号' },
        ]"
      />
      <van-field
        v-model="form.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { loginAPI } from '@/api/userAPI.js'
export default {
  // 组件的name属性的值,首字母大写
  name: 'Login',
  data () {
    return {
      form: {
        mobile: '13845674567',
        code: '246810'
      }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']),
    // 表单提交事件
    async onSubmit () {
      const { data: res } = await loginAPI(this.form)
      if (res.message === 'OK') {
        // 证明登录成功
        // 1.把token存储到本地
        // localStorage.setItem('token', JSON.stringify(res.data))
        this.updateTokenInfo(res.data)
        // 2.跳转页面
        // 动态获取登录成功之后要导航到那个地址
        const navPath = this.$route.query.pre || '/'
        this.$router.replace(navPath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  padding-top: 46px;
}
</style>
